package com.heima.service;

import com.heima.config.MinioProperties;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    public String uploadFile(MultipartFile file) throws IOException, NoSuchAlgorithmException, InvalidKeyException, MinioException {
        String bucketName = minioProperties.getBucketName();
        String fileName = file.getOriginalFilename();
        String endpoint = minioProperties.getEndpoint();
        // 上传文件
        try {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }

        // 生成文件访问 URL
        return endpoint+"/"+bucketName+"/"+fileName;
    }
}
